import React, { Component } from "react";
import { Link, Route, Switch, Redirect, withRouter } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>首页</div>;
  }
}
class About extends Component {
  render() {
    return <div>关于页</div>;
  }
}
class Mine extends Component {
  render() {
    return <div>我的页</div>;
  }
}

@withRouter
class Login extends Component {
  login = () => {
    localStorage.setItem("token", 345345);
    // console.log(this.props);
    const { history } = this.props;
    history.replace({
      pathname: this.props.location.state.from,
    });
  };

  render() {
    console.log(this.props);
    return (
      <div>
        登录页 - <button onClick={this.login}>登录</button>
      </div>
    );
  }
}

// 路由鉴权的组件封装
const Auth = (props) => {
  return (
    <Route
      path={props.path}
      render={() => {
        return localStorage.getItem("token") ? (
          props.children
        ) : (
          <Redirect
            from={props.path}
            to={{
              pathname: "/login",
              state: { from: props.path },
            }}
          ></Redirect>
        );
      }}
    ></Route>
  );
};

class Basic extends Component {
  state = {};
  render() {
    return (
      <>
        <h3>路由鉴权</h3>
        <ul>
          <li>
            <Link to="/home">home</Link>
          </li>
          <li>
            <Link to="/about">about</Link>
          </li>
          <li>
            <Link to="/mine">mine</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/home" component={Home} exact></Route>
          {/* <Route path="/about" component={About}></Route> */}
          {/* <Route
            path="/mine"
            render={() => {
              if (localStorage.getItem("token")) {
                return <Mine />;
              } else {
                return <Redirect to="/login"></Redirect>;
              }
            }}
          ></Route> */}
          <Auth path="/about">
            <About />
          </Auth>
          <Auth path="/mine">
            <Mine />
          </Auth>

          {/* <Route path="/login" component={Login}></Route> */}
          <Route>
            <Login />
          </Route>
        </Switch>
      </>
    );
  }
}

export default Basic;
